#include "maininterpreter.h"

MainInterpreter::MainInterpreter(Api &api, QObject *parent)
	: AInterpreter(api, parent)
{
	_proto = (byte)MAIN;
	operatorsFunc[(byte)BROADCAST] = (funcPtr)&MainInterpreter::manageBroadcast;
	operatorsFunc[(byte)CONNECT] = (funcPtr)&MainInterpreter::manageConnect;
	operatorsFunc[(byte)NAME] = (funcPtr)&MainInterpreter::manageName;
}

MainInterpreter::~MainInterpreter()
{

}

void					MainInterpreter::manageBroadcast(Packet &pkg)
{
	QHostAddress		ip = QHostAddress(QString().fromStdString(pkg.getFrom()));
	quint16				id;
	clientInfo			info;

	if (!_api.network()->isInside(ip))
	{
		id = _api.network()->connectTo(ip.toString().toStdString(), "4242");
		_api.client()->addClient( id );
		info = _api.client()->getClient(id);
		_api.gui()->addServer(id, info._name);
	}
}

void					MainInterpreter::manageBroadcastTimer(Packet &pkg)
{
	QHostAddress		ip = QHostAddress(QString().fromStdString(pkg.getFrom()));
	quint16				id;
	clientInfo			info;
	unsigned int		time = pkg.getData<unsigned int>(1)[0];

	if (!_api.network()->isInside(ip))
	{
		id = _api.network()->connectTo(ip.toString().toStdString(), "4242");
		_api.client()->addClient( id );
		info = _api.client()->getClient(id);
		_api.gui()->addServer(id, info._name);
	}
	_api.timer()->setTime(time);
}

void					MainInterpreter::manageConnect(Packet &pkg)
{
	State				state = pkg.getData<State>(1)[0];
	QHostAddress		ip = QHostAddress(QString().fromStdString(pkg.getFrom()));
	quint16				id = _api.network()->getId(ip);

	if (state == OK)
	{
		qDebug() << "Connected to id " << id << "with ip" << ip;
		_api.gui()->displayMessage("Unisound Client", std::string("You're now connected to ") + ip.toString().toStdString());
		_api.client()->setConnected(true, id);
	}
	else if (state == KO)
	{
		_api.gui()->displayMessage("Unisound Client", "Impossible to connect");
		qDebug() << "Impossible to connect.";
		//_api.network()->removeClient(id);
		//_api.client()->removeClient(id);
		//_api.gui()->removeServer(id);
	}
}

void					MainInterpreter::manageName(Packet &pkg)
{
	QHostAddress		ip = QHostAddress(QString().fromStdString(pkg.getFrom()));
	quint16				id = _api.network()->getId(ip);

	unsigned int		nameSize = pkg.getData<unsigned int>(1)[0];
	char				*name = pkg.getData<char>(nameSize);

	_api.client()->setName(QString(name), id);
	_api.gui()->changeName(id, QString(name));
}